var express = require("express");
var router = express.Router();
var bcrypt = require("bcryptjs");
var userModel = require("../models/userModel");
var saltRound = 10; //盐，加密复杂度

// token使用
var jwt = require("jsonwebtoken");
var secret = "ljljljljasdfa";

/* GET users listing. */
router.get("/reg/page", function (req, res, next) {
  let path = __dirname.split("routes")[0];
  res.sendFile(path + "views/reg.html");
});

/**
 * @api {post} /users/reg UserRegister
 * @apiDescription 用户账号注册
 * @apiName UserRegister
 * @apiGroup User
 * @apiBody {String} username 账号
 * @apiBody {String} pwd 密码
 * @apiBody {String} email 邮箱
 * @apiUse CommonSuccess
 * @apiSuccessExample {json} Success-Response:
 * HTTP/1.1 200 OK
 *  {
 *      "code" : 1,
 *      "msg": "注册成功"
 *  }
 * @apiSampleRequest /users/reg
 * @apiVersion 1.0.0
 */
router.post("/reg", function (req, res, next) {
  console.log(req.body);
  // 1. 判断该用户名是否已存在
  // 2. 存储新用户信息
  let { username, pwd, email } = req.body;
  userModel.find({ username: username }).then((result) => {
    if (result.length != 0) {
      //该用户名已被占用
      res.send({
        code: 0,
        msg: "用户名已存在",
      });
      return false;
    }
    bcrypt.hash(pwd, saltRound, (err, hashPwd) => {
      //如果用户名可用，则对用户密码进行加密
      if (!err) {
        new userModel({
          //实例化一个新的用户对象
          username: username,
          pwd: hashPwd,
          email,
        })
          .save()
          .then((result) => {
            //录入新用户至MongoDB数据库
            res.send({
              code: 1,
              msg: "注册成功",
            });
          });
      }
    });
  });
});

/**
 * @api {get} /users/login UserLogin
 * @apiDescription 用户登录
 * @apiName UserLogin
 * @apiGroup User
 * @apiQuery {String} username 账号
 * @apiQuery {String} pwd 密码
 * @apiUse CommonSuccess
 * @apiSuccess {String} data token令牌-请求特定接口需要携带
 * @apiSuccess {String} id 用户id
 * @apiSuccessExample {json} Success-Response:
 * HTTP/1.1 200 OK
 *  {
 *      "code" : 1,
 *      "msg": "登录成功",
 *      "data":{
 *         "id":"用户id",
 *         "token":"token令牌"
 *      }
 *  }
 * @apiSampleRequest /users/login
 * @apiVersion 1.0.0
 */

router.get("/login", function (req, res) {
  let { username, pwd } = req.query;
  console.log(username);
  userModel.find({ username }).then((result) => {
    if (result.length == 0) {
      //查看用户是否存在
      res.send({
        code: 0,
        msg: "用户不存在",
      });
      return false;
    }
    let hashPwd = result[0].pwd; //获取用户注册时录入数据库的加密密吗
    bcrypt.compare(pwd, hashPwd, function (err, data) {
      //对比密码是否正确
      if (data) {
        let token = jwt.sign({ login: true }, secret); //生成token 下发给登录成功的用户
        res.send({
          code: 1,
          msg: "登录成功",
          data: {
            token,
            id: result[0]._id,
          },
        });
      } else {
        res.send({
          code: 1,
          msg: "密码错误",
        });
      }
    });
  });
});

router.get("/token/verify", function (req, res) {
  //判断用户token是否合法
  jwt.verify(req.query.token, secret, function (err, data) {
    if (!err) {
      res.send({
        code: 1,
        msg: "token合法",
      });
    } else {
      res.send({
        code: 0,
        msg: "token非法，请重新登录",
      });
    }
  });
});

module.exports = router;
